package main

import (
	"syscall/js"
	"xiaowu"
	"xiaowu/pkg/core"
)

func main() {
	js.Global().Set("__version", js.FuncOf(version))
	js.Global().Set("__latest", js.FuncOf(latest))
	js.Global().Set("__translate", js.FuncOf(translate))
	<-make(chan int)
}

func version(this js.Value, args []js.Value) any {
	return xiaowu.Version
}

func latest(this js.Value, args []js.Value) any {
	return map[string]any{
		"Latest":     xiaowu.Version,
		"ReleaseURL": "n/a",
	}
}

func translate(this js.Value, args []js.Value) any {
	if len(args) < 1 {
		panic("bad request")
	}
	word := args[0].String()
	translated, comment, debug, err1 := core.Translate(word)
	err := ""
	if err1 != nil {
		err = err1.Error()
	}
	return map[string]any{
		"Word":       word,
		"Translated": translated,
		"Comment":    ToGenericArray(comment),
		"Debug":      ToGenericArray(debug),
		"Err":        err,
	}
}

func ToGenericArray[T any](arr []T) []any {
	ret := make([]any, 0, len(arr))
	for _, v := range arr {
		ret = append(ret, v)
	}
	return ret
}
